const axios = require('axios');
const crypto = require('crypto');
const Promise = require('bluebird');
const cache = require('../services/cache');

const WECHAT_BASE = 'https://api.weixin.qq.com/cgi-bin';
const api = this.api = axios.create({
    baseURL: WECHAT_BASE,
    responseType: 'json',
    timeout: 2000
});

    // 返回数据格式化
api.interceptors.response.use(res => {
    let data = res.data;
    if(data && res.status === 200) {
        // 裁剪数据
        res.data = data.data;
        res.result = data;
        return res;
    }

    let msg = data && data.msg || '请求失败 unknow error';

    // debug
    if(process.env.NODE_ENV === 'development') {
        msg += ' ' + JSON.stringify(data);
    }

    let err = new Error(`WECHAT_API: ${msg}`);

    // error props
    err.config = res.config;
    err.response = res;
    err.data = data;

    return Promise.reject(err);
}, err => {
    return Promise.reject(err);
});

api.https = function(options) {
    return Promise.try(() => {
        return api.request(options);
    })
    .then(res => {
        // cache.set('wehcat_access_token', res.result.access_token, 7200)
        // .then(() => {
        //     console.log('cache');
        // });
        return res.result;
    });
};

// noncestr
var createNonceStr = function() {
    return Math.random().toString(36).substr(2, 15);
};

// timestamp
var createTimeStamp = function() {
    return parseInt(new Date().getTime() / 1000);
};

module.exports = {
    getToken: function() {
        return cache.get('wehcat_access_token')
        .then((data) => {
            if(!data || data === 'undefined' || data === 'null') {
                return api.https({
                    method: 'get',
                    params: {
                        grant_type: 'client_credential',
                        appid: process.env.WECHAT_APPID,
                        secret: process.env.WECHAT_SECRET
                    },
                    url: '/token'
                })
                .then((res) => {
                    cache.set('wehcat_access_token', res.access_token, 7200);
                    return res.access_token;
                });
            }
            return data;
        });
    },
    getTicket: function(accessToken) {
        return cache.get('wehcat_ticket')
        .then((data) => {
            if(!data || data === 'undefined' || data === 'null') {
                return api.https({
                    method: 'get',
                    params: {
                        access_token: accessToken,
                        type: 'jsapi'
                    },
                    url: '/ticket/getticket'
                })
                .then((res) => {
                    cache.set('wehcat_ticket', res.ticket, 7200);
                    return res.ticket;
                });
            }
            return data;
        });
    },
    signature: function(ticket, url) {
        const noncestr = createNonceStr();
        const ts = createTimeStamp();
        const str = 'jsapi_ticket=' +
                    ticket +
                    '&noncestr=' +
                    noncestr +
                    '&timestamp=' +
                    ts +
                    '&url=' + url;
        let shasum = crypto.createHash('sha1');
        shasum.update(str);
        const signature = shasum.digest('hex');
        return {
            appId: process.env.WECHAT_APPID,
            signature: signature,
            nonceStr: noncestr,
            timestamp: ts
        };
    }
}

